package com.chenpeixin;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.*;

public class JDBCNotSelectDemo {
    public static void main(String[] args) throws SQLException {
        MysqlDataSource ds = new MysqlDataSource();
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/db_11_24?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");
        ds.setUser("root");
        ds.setPassword("123456");
        try (Connection c = ds.getConnection()) {
            String sql = "insert into exam_result (name, chinese, math, english) values ('二郎神', 38, 99, 78.5)";

            // 要得到自增 id，这么去控制
            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                // 不是查询的语句
                int affectRow = s.executeUpdate();
                System.out.println("影响行数: " + affectRow);

                try (ResultSet rs = s.getGeneratedKeys()) {
                    // 因为知道只有一行 id 返回
                    rs.next();  // 让游标走到第一行上
                    int pk = rs.getInt(1);  // 无法用列名称，只能用下标，取第一个值
                    System.out.println(pk);
                }
            }
        }
    }

    public static void main2(String[] args) throws SQLException {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/db_11_24?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        try (Connection connection = mysqlDataSource.getConnection()) {
            String sql = "insert into exam_result (name, chinese, math, english) values ('哪吒', 38, 99, 78.5)";
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                // 不是查询的语句
                int affectRow = preparedStatement.executeUpdate();
                System.out.println("影响行数: " + affectRow);
            }
        }
    }
}
